package com.pe.pgn.clubpgn.webapp.controller.segmentacion;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;

import com.pe.pgn.clubpgn.domain.ClpbSegmentacion;
import com.pe.pgn.clubpgn.service.SegmentacionService;
import com.pe.pgn.clubpgn.webapp.controller.BaseFormController;

@Controller
@RequestMapping("**/segmentacion/*")
public class SegmentacionController extends BaseFormController{

	@Autowired
	private SegmentacionService segmentacionService;
	
	@RequestMapping(value = "/segmentacionlist.html", method = RequestMethod.GET)
	public void listarSegmentos(Model model) {
		List<ClpbSegmentacion> lista = segmentacionService.obtenerSegmentaciones();
		model.addAttribute("clpbsegmentacion", new ClpbSegmentacion());        
		model.addAttribute("listaSegmentos", lista);
	}
	
	@RequestMapping(value = "/eliminarsegmento.html")
	public String eliminarSegmento(@RequestParam(value = "id", required = false) Long id, 
		HttpServletRequest request, ModelMap model){
		
		segmentacionService.eliminarSegmento(id);
		saveMessage(request, getText("segmentacionform.deleted", request.getLocale()));
		return "redirect:segmentacionlist.html";
	}
	
	@RequestMapping(value = "/segmentacionform.html", method = RequestMethod.POST)
	public String guardarSegmentacion(@ModelAttribute("clpbsegmentacion") ClpbSegmentacion clpbSegmentacion,
		BindingResult result, SessionStatus status, HttpServletRequest request) {
		
		try{
			
			if (result.hasErrors()) {
				List<ObjectError> listError = result.getAllErrors();
				FieldError error = (FieldError)listError.get(0);
				saveError(request, error.getDefaultMessage());
				return "redirect:segmentacionlist.html";
			}
			
			boolean isValidate = segmentacionService.validarTraslapoCondicion(clpbSegmentacion);
			if(!isValidate){
				saveError(request, getText("segmentacionform.traslapo", request.getLocale()));
				return "redirect:segmentacionlist.html";
			}
			
			clpbSegmentacion.setStSegmentacion(true);
			segmentacionService.guardarSegmentacion(clpbSegmentacion);
			saveMessage(request, getText("segmentacionform.added",request.getLocale()));
			return "redirect:segmentacionlist.html";
			
		} catch (Exception e) {
			saveError(request, getText("errors.general", request.getLocale()));
			return "redirect:segmentacionlist.html";
		}
	}
}
